package com.apimarket.util.net;

import com.apimarket.enums.NetContextEnum;
import com.apimarket.exception.NetContextException;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class DeleteNetContext extends NetContext {
    private CloseableHttpClient client;

    private HttpDelete httpDelete;

    private static final int SUCCESS_CODE = 204;

    public DeleteNetContext(String url) {
        super(url, null);
        this.client = HttpClients.createDefault();
        this.httpDelete = new HttpDelete();
    }

    @Override
    public JsonNode getResultJson() throws IOException, URISyntaxException {
        httpDelete.setURI(new URI(getUrl()));
        try (CloseableHttpResponse response = client.execute(httpDelete)) {
            int code = response.getStatusLine().getStatusCode();
            if (code == SUCCESS_CODE) return null;
            else throw new NetContextException(NetContextEnum.DELETE_ERROR);
        }
    }
}
